# # 利用tailhead软件包跟踪文件变化
import tailhead
import parse
import fire
import time
import datetime
import os
import random
import regex as re
from math import sin

# 调用客户端
from thingsboard_gateway.tb_client.tb_device_mqtt import TBDeviceMqttClient
# 输出log，便于调试
import logging

def main(host='test2.bj-jiashi.com',
        port=10006,
        token='picarro', 
        delay_time=0.5, 
        target_log_file='sub1_picarro_simulator.py.test.log',
        log_level = 'INFO'):
    """假造一些输出到log文件，模拟实际设备
    """
    # 初始化
    logging.basicConfig(level = getattr(logging,log_level.upper(),logging.INFO)) # 默认info
    file_base_name = os.path.basename(__file__)
    logger = logging.getLogger(file_base_name)

    # header
    # 分隔符
    #sep = ' '
    
    col_width = 26 # 固定列宽格式
    # 列名
    header = 'DATE                      TIME                      FRAC_DAYS_SINCE_JAN1      FRAC_HRS_SINCE_JAN1       JULIAN_DAYS               EPOCH_TIME                ALARM_STATUS              INST_STATUS               CavityPressure            CavityTemp                DasTemp                   EtalonTemp                WarmBoxTemp               species                   MPVPosition               OutletValve               solenoid_valves           CO                        CO2                       CO2_dry                   CH4                       CH4_dry                   H2O                       h2o_reported              b_h2o_pct                 peak_14                   peak84_raw                '
        # 第一行
    logger.info(header)
    
    col_names = [header[i*col_width:i*col_width+col_width].strip() for i in range(len(header)//col_width)]
    # re.sub('[^a-zA-Z0-9]','_',n.strip())
    # 把'Temperature(°C)'转化为'Temperature__C_'

    # 非时间的类型
    # 尾部是STATUS的认为是
    types =['s']*2+ ['.8f','.6f','.8f','.3f'] + ['d' if col.endswith('STATUS') else '.10e' for col in col_names[6:]]

    # data types
    data_types =  dict(zip(col_names, types))
    
    data_read_formats = [format[-1] for format in types] # s,d,e

    # selected cols
    selected_cols = col_names[6:] # skip all kinds of times
    
    # 默认值，为保持完整性
    defaults_str = '2020-12-04                22:15:31.657              339.26078308              8142.258794               340.26078308              1607120131.658            0                         963                       1.3999922362E+02          4.5000114441E+01          3.4212167406E+01          4.5304435730E+01          4.5000236511E+01          4.0000000000E+00          0.0000000000E+00          3.1923543297E+04          0.0000000000E+00          4.2624762096E-01          4.4728279991E+02          4.4962323590E+02          2.2627866372E+00          2.2725807459E+00          3.3528346203E-01          4.2964400486E-01          4.7567853250E-01          6.3450717542E+02          9.8725673361E-01          '
   
    # 建立设备连接
    TBD = TBDeviceMqttClient(host, port, token)
    TBD.connect()
    logger.info('mqtt server connected!')

    for line in tailhead.follow_path(target_log_file,encoding='utf-8'):
        if line is not None:
            logger.info(f"readline: {line}")
            # 解析
            sections  = line.split()
            vals = []
            for f,section in zip(data_read_formats,sections):
                if f in 's':
                    val = section.strip()
                    
                elif f in 'feg':
                    val = float(section)
                    
                elif f in 'dn':
                    val = int(section)
                    
                else:
                    raise RuntimeError(f'unknown format {f}')
                vals.append(val)

            data_line_dict = dict(zip(col_names,vals))

            # 构造tb上传的字典
            data_dict = {'ts':-1,'values':{}}

            # 时间处理
            data_dict['ts'] = int(data_line_dict['EPOCH_TIME']*1000) # 转换为ms数

            # 数据抽取
            data_dict['values'] = {k:data_line_dict.get(k,-99999) for k in selected_cols}

            logger.info(f'data_dict={data_dict}')

            # 上传
            TBD.send_telemetry(data_dict)
            time.sleep(delay_time)

        else:
            logger.info('sleep.')
            time.sleep(delay_time)
if __name__ == "__main__":
    fire.Fire(main) # 利用fire命令行化
